/*
 * @FilePath: /fxfzywpt/src/utils/sqlTempLayersSet.js
 * @Description:
 */
import { getRESTLayer } from '@/map/projMap.js';
import { MapService } from '@supermap/iclient-ol';
/**
 * 根据sqltext查询临时图层
 * @param {string} layerUrl
 * @param {string} sqlText
 * @returns
 */
//地图服务网址
export function iServerHttp() {
  return import.meta.env.VITE_APP_MAP_URL;
  // return "http://10.13.155.192:8090"
  // return "http://10.7.209.199:8090"
  //代理
  // return "http://10.7.208.233:8080"
}

export async function getSqlTempLayer(url, sqlText) {
  let layerUrl = iServerHttp() + url;
  return new Promise(async (resolve, reject) => {
    let obj = null;
    try {
      obj = await getLayersRJson(layerUrl);
    } catch (error) {
      console.log(error);
      reject(error);
    }

    console.log('==============obj: ', obj);
    if (!obj) {
      reject('获取图层失败');
      return;
    }
    if (sqlText != null && sqlText != '') {
      for (let i = 0; i < obj.length; i++) {
        let layers = obj[i].subLayers.layers;
        for (let j = 0; j < layers.length; j++) {
          layers[j].displayFilter = sqlText; //SQL查询过滤
        }
      }
    }
    let layersData = await postTempLayersSet(layerUrl, obj); //创建并获取超图临时图层

    console.log('==============layersData: ', layersData);
    if (layersData) {
      let layerID = layersData.newResourceID;
      let newResourceLocation = layersData.newResourceLocation;
      //瓦片地图图层
      let mapService = new MapService(layerUrl); //根据超图REST图层获取图层信息
      mapService.getMapInfo(async function (serviceResult) {
        if (serviceResult.result != undefined) {
          let mapJSONObj = serviceResult.result;
          console.log(mapJSONObj);
          //获取超图发布的REST图层
          //let options = TileSuperMapRest.optionsFromMapJSON(layerUrl, mapJSONObj);
          let layerName = mapJSONObj.name; //图层名称
          //获取图层范围
          let bounds = mapJSONObj.bounds;
          let left = bounds.left;
          let bottom = bounds.bottom;
          let right = bounds.right;
          let top = bounds.top;
          let origin = [left, top]; //左上角
          let extent = [left, bottom, right, top]; //图层范围
          //获取超图发布的REST图层（自定义比例尺）
          let layer = await getRESTLayer(layerUrl, layerID, origin, extent, mapJSONObj, 17);
          resolve(layer);
        } else {
          reject('图层请求失败');
        }
      });
    }
  });
}

export function getLayersRJson(layerUrl) {
  let url = encodeURI(layerUrl + '/layers.rjson');
  return new Promise((resolve, reject) => {
    //查询REST图层信息
    let httpRequest = new XMLHttpRequest(); //第一步：建立所需的对象
    httpRequest.open('GET', url, true); //第二步：打开连接  将请求参数写在url中
    httpRequest.send(); //第三步：发送请求  将请求参数写在URL中
    //获取数据后的处理程序
    httpRequest.onreadystatechange = function () {
      if (httpRequest.readyState == 4 && httpRequest.status == 200) {
        let json = httpRequest.responseText; //获取到json字符串，还需解析
        let obj = JSON.parse(json);
        if (obj.length > 0) {
          resolve(obj);
        } else {
          reject('图层请求失败');
        }
      } else if (httpRequest.readyState == 4 && httpRequest.status != 200) {
        reject('图层请求失败');
      }
    };
  });
  //   return request({
  //     baseURL: import.meta.env.VITE_APP_MAP_BASE_API,
  //     url: `${layerUrl}/layers.rjson`,
  //     method: 'get',
  //   });
}
export function postTempLayersSet(layerUrl, obj) {
  return new Promise((resolve, reject) => {
    let url = encodeURI(layerUrl + '/tempLayersSet.rjson');
    let entry = JSON.stringify(obj);
    let xhr = new XMLHttpRequest(); //第一步：建立所需的对象
    xhr.open('POST', url, true); //第二步：打开连接  将请求参数写在url中
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    //获取数据后的处理程序
    xhr.onreadystatechange = function () {
      let readyState = xhr.readyState;
      if (readyState == 4) {
        let status = xhr.status;
        let responseText = xhr.responseText;
        let result = JSON.parse(responseText);
        if (result.succeed) {
          resolve(result);
        } else {
          //that.$message({ message: '创建临时图层失败!', type: 'warning' });
        }
        xhr.onreadystatechange = function () {};
        xhr = null;
      }
    };
    xhr.send(entry); //第三步：发送请求  将请求参数写在URL中
  });
  //   return request({
  //     baseURL: import.meta.env.VITE_APP_MAP_BASE_API,
  //     url: `${layerUrl}/tempLayersSet.rjson`,
  //     method: 'post',
  //     data: entry,
  //   });
}
